/**
 * Created by Administrator on 2017/10/24
 */
import * as mobx from 'mobx';
import { WeaTools, WeaLocaleProvider } from 'ecCom';
import { ListStore } from './listStore';
import { WeaForm } from 'comsMobx';
import { message, Modal, Button } from 'antd';
import * as WORKFLOW_AGENT from '../apis/agent';

const getLabel = WeaLocaleProvider.getLabel;
const { observable, action } = mobx;
const Base64 = WeaTools.Base64;

export class WFAgentStore extends ListStore {

    urlParams = {};
    @observable addAgentVisible = false;   //添加代理弹出框
    @observable editAgentVisible = false;   //编辑代理和另存为弹出框
    @observable batchEditVisible = false;    //批量编辑弹出框
    backRunning = 1;//是否收回代理中的流程


    @observable agented = 0;   //切换流程代理和已办代理，0为流程代理，1为已办代理。
    @observable agentFlag = 0; //切换tab页标志,0为我的待办，或者带我处理的。1为其他人的待办，或者我代为处理的。

    agentid = '';
    wfInfo = {};
    addAgentFlag = 'addAgent';         //标记是哪儿打开的添加代理的组件
    highSearchInitDate = {};

    @observable agentConditionData = [];   //代理条件中的数据

    originalConditionData = [];    //记录编辑中最初的table数据
    @observable ismodifyCondition = false;    //标记table数据是否做了修改
    editAndSaveOtherSymbol = '';   //标记是另存为还是编辑

    @observable addAgentForm = new WeaForm();
    @observable editAgentForm = new WeaForm();
    @observable batchEditForm = new WeaForm();

    @observable addAgentDatas = {};
    @observable editAgentDatas = {};
    @observable batchEditDatas = {};

    @observable viewcondition = 0;     //标志tabs
    @observable repetitionValue = 0;  //重复条数
    overlapIds = '';
    userSelect = {};    //保存userSelect信息的临时变量
    @observable selectedRowKeys = [];   //记录代理条件中选择的ids
    @observable isDisabled = false;    //按钮禁用标记
    ////////start by lijia 2018-12-06
    dialogE9;
    isE9Rule = false;

    ////////end by lijia 2018-12-06


    constructor() {
        super();
        //this.title = getLabel(17723, '流程代理');
        this.initDatas = this.initDatas.bind(this);
        this.doSearch = this.doSearch.bind(this);
        this.addAgent = this.addAgent.bind(this);
        this.setConditionByTree = this.setConditionByTree.bind(this);
        this.editAgent = this.editAgent.bind(this);
        this.setParams = this.setParams.bind(this);
        this.setViewcondition = this.setViewcondition.bind(this);
        this.batchEdit = this.batchEdit.bind(this);
        this.verifyAgentOverlap = this.verifyAgentOverlap.bind(this);
        this.dataSave = this.dataSave.bind(this);
        this.initTimeStartValue = this.initTimeStartValue.bind(this);
        this.startDateChange = this.startDateChange.bind(this);
        this.endDateChange = this.endDateChange.bind(this);
        this.startTimeChange = this.startTimeChange.bind(this);
        this.endTimeChange = this.endTimeChange.bind(this);
        this.verifyTime = this.verifyTime.bind(this);
        this.clearFormFields = this.clearFormFields.bind(this);
        this.reload = this.reload.bind(this);
        this.bagentuidChange = this.bagentuidChange.bind(this);
        this.saveAgentTemplate = this.saveAgentTemplate.bind(this);
        this.setAgentConditionData = this.setAgentConditionData.bind(this);
        this.setIsmodifyCondition = this.setIsmodifyCondition.bind(this);
        this.doAddAgentInit = this.doAddAgentInit.bind(this);
    }

    @action
    setUrlParams(params = {}) {
        this.urlParams = params;
    }

    initDatas(params = {}) {
        this.title = getLabel(17723, '流程代理');
        if(params.tabTitle){
            this.title = Base64.decode(decodeURIComponent(params.tabTitle));
        }
        const agented = this.agented;
        const agentFlag = this.agentFlag;
        this.form = new WeaForm();
        WORKFLOW_AGENT.getWfHighSearch({ agented, agentFlag, ...params }).then((datas) => {
            this.condition = datas.condition;
            this.form.initFormFields(datas.condition);
            this.highSearchInitDate = datas.formValue;
            this.form.updateFields(datas.formValue, false);
        });
    }

    doSearch(params = {}) {
        const agented = this.agented;
        const agentFlag = this.agentFlag;
        this.loading = true;
        const searchParamsAd = this.form.getFormParams();
        const newParams = { ...searchParamsAd, ...params, agented, agentFlag };
        WORKFLOW_AGENT.getWfAgentList(newParams).then((datas) => {
            const { sessionkey } = datas;
            this.resetTable(true);
            this.tableStore.getDatas(sessionkey, params.current || 1);
            this.loading = false;
        });
    }

    setIsmodifyCondition(flag = false) {
        this.ismodifyCondition = flag;
    }

    setSelectedRowKeys(selectedRowKeys = []) {
        this.selectedRowKeys = selectedRowKeys;
    }
    //被代理人发生改变
    bagentuidChange(params = false) {
        if (params) {
            this.addAgentDatas.userSelect = this.userSelect;

        } else {
            delete this.addAgentDatas.userSelect;
        }
    }

    addAgent(visible = false, params = {}) {
        if (!visible) {
            this.addAgentForm.resetConditionValue();
            this.addAgentVisible = false;
        } else {
            this.doAddAgentInit(params, true);
        }
    }

    doAddAgentInit(params = {}, fromModal) {
        WORKFLOW_AGENT.getWfNewAgent({ ...params, ...this.urlParams }).then((datas) => {
            this.addAgentForm = new WeaForm();
            this.addAgentDatas = datas.fields;

            if (datas.fields.hasOwnProperty('userSelect')) {
                this.userSelect = datas.fields.userSelect;
                // const userid = WeaTools.ls.getJSONObj('theme-account').userid;
                if (datas.userId === datas.formValue.bagentuid.value) {
                    this.bagentuidChange(true);
                } else {
                    this.bagentuidChange(false);
                }
            }
            //时间选择范围初始化
            if (params.symbol === 'addAgent' || params.symbol === 'importTemplate') {
                this.initTimeStartValue('addAgentDatas');
            }

            this.addAgentForm.initFormFieldObj(datas.fields);

            //form初始值
            if (datas.hasOwnProperty('formValue')) {
                this.addAgentForm.updateFields({
                    isProxyDeal: { value: "1" },
                    agentrange: { value: "1" },
                    isCreateAgenter: { value: "0" },
                    ...datas.formValue
                }, true);

            } else {
                this.addAgentForm.updateFields({
                    isProxyDeal: { value: "1" },
                    agentrange: { value: "1" },
                    isCreateAgenter: { value: "0" }
                }, true);
            }

            this.addAgentFlag = params.symbol;
            if (params.symbol === 'editTemplate') {
                this.agentid = params.templateid;
            }
            window.e9ChangedFormFieldKey = 'tttsgfdgfhdffs';
            // if(fromModal)
            this.addAgentVisible = true;
        });
    }

    setAgentConditionData(datas = []) {
        this.agentConditionData = [...datas];
    }

    editAgent(visible = false, params = {}) {
        if (!visible) {
            this.editAgentVisible = false;
        } else {
            WORKFLOW_AGENT.editAndSaveOther(params).then((datas) => {
                this.editAgentForm = new WeaForm();
                this.agentid = params.agentid;
                this.editAgentDatas = datas.fields;
                this.wfInfo = datas.wfInfo;
                this.agentConditionData = datas.datas;
                this.originalConditionData = datas.datas;
                this.editAndSaveOtherSymbol = params.symbol;
                /////start by lijia 2018-12-06
                this.isE9Rule = datas.isE9Rule || false;
                /////end by lijia 2018-12-06
                //时间选择范围初始化
                this.initTimeStartValue('editAgentDatas');
                this.editAgentForm.initFormFieldObj(datas.fields);
                this.editAgentForm.updateFields(datas.formValue, true);
                this.selectedRowKeys = [];
                this.editAgentVisible = true;
            });
        }

    }


    //批量编辑modal切换
    batchEdit(visible = false, ids = '') {
        if (!visible) {
            this.batchEditVisible = false;
        } else {
            this.agentid = ids;
            WORKFLOW_AGENT.getWfBatchEdit().then((datas) => {
                this.batchEditForm = new WeaForm();
                this.batchEditDatas = datas.fields;
                //初始时间范围
                this.initTimeStartValue('batchEditDatas');
                setTimeout(() => {
                    this.batchEditForm.initFormFieldObj(datas.fields);
                    this.batchEditForm.reset();
                }, 0)

                this.batchEditVisible = true;
            })
        }

    }

    //初始化日期的startValue

    initTimeStartValue(datasFlag) {

        let nowTime = new Date();
        let startValue = nowTime.getFullYear() + '-' + (parseInt(nowTime.getMonth()) + 1) + '-' + nowTime.getDate();

        if (datasFlag === 'batchEditDatas') {
            this.batchEditDatas.beginDate.startValue = startValue;
            this.batchEditDatas.endDate.startValue = startValue;
        } else if (datasFlag === 'addAgentDatas') {
            this.addAgentDatas.beginDate.startValue = startValue;
            this.addAgentDatas.endDate.startValue = startValue;
        } else if (datasFlag === 'editAgentDatas') {
            this.editAgentDatas.beginDate.startValue = startValue;
            this.editAgentDatas.endDate.startValue = startValue;
        }

    }

    //开始结束时间的限制

    startDateChange(obj, datasFlag) {

        if (datasFlag === 'batchEditDatas') {

            if (obj.beginDate.value === '') {
                let nowTime = new Date();
                let startValue = nowTime.getFullYear() + '-' + (parseInt(nowTime.getMonth()) + 1) + '-' + nowTime.getDate();
                this.batchEditDatas.endDate.startValue = startValue;

                return;
            }
            this.batchEditDatas.endDate.startValue = obj.beginDate.value;

        } else if (datasFlag === 'addAgentDatas') {

            if (obj.beginDate.value === '') {
                let nowTime = new Date();
                let startValue = nowTime.getFullYear() + '-' + (parseInt(nowTime.getMonth()) + 1) + '-' + nowTime.getDate();
                this.addAgentDatas.endDate.startValue = startValue;
                return;
            }
            this.addAgentDatas.endDate.startValue = obj.beginDate.value;
        } else if (datasFlag === 'editAgentDatas') {
            if (obj.beginDate.value === '') {
                let nowTime = new Date();
                let startValue = nowTime.getFullYear() + '-' + (parseInt(nowTime.getMonth()) + 1) + '-' + nowTime.getDate();
                this.editAgentDatas.endDate.startValue = startValue;
                return;
            }
            this.editAgentDatas.endDate.startValue = obj.beginDate.value;
        }


    }

    endDateChange(obj, datasFlag) {

        if (datasFlag === 'batchEditDatas') {

            if (obj.endDate.value === '') {
                this.batchEditDatas.beginDate.endValue = '';
                return;
            }

            let date = new Date(obj.endDate.value.replace(/-/g, '/'));
            date.setDate(date.getDate());
            let endValue = date.getFullYear() + '-' + (parseInt(date.getMonth()) + 1) + '-' + date.getDate();
            this.batchEditDatas.beginDate.endValue = endValue;

        } else if (datasFlag === 'addAgentDatas') {

            if (obj.endDate.value === '') {
                this.addAgentDatas.beginDate.endValue = '';
                return;
            }

            let date = new Date(obj.endDate.value.replace(/-/g, '/'));
            date.setDate(date.getDate());
            let endValue = date.getFullYear() + '-' + (parseInt(date.getMonth()) + 1) + '-' + date.getDate();
            this.addAgentDatas.beginDate.endValue = endValue;

        } else if (datasFlag === 'editAgentDatas') {
            if (obj.endDate.value === '') {
                this.editAgentDatas.beginDate.endValue = '';
                return;
            }

            let date = new Date(obj.endDate.value.replace(/-/g, '/'));
            date.setDate(date.getDate());
            let endValue = date.getFullYear() + '-' + (parseInt(date.getMonth()) + 1) + '-' + date.getDate();
            this.editAgentDatas.beginDate.endValue = endValue;
        }


    }
 

    ///////start by lijia 2018-12-06


    //e9规则设计器
    openeE9RuleDesign = (rowindex, params, ecId) => {
        const btns = ([(< Button ecId={`${ecId}_Button@t5qc7s@close`} type="primary" onClick={this.onSave} > {getLabel(309, `关闭`)} </Button>)])
        let url = `/spa/workflow/static4engine/engine.html#/main/workflowengine/path/exportConditionSetting?rulesrc=6&formid=${params.formid}&isbill=${params.isbill}&linkid=${params.linkid}&isnew=1&wfid=${params.wfid}&rownum=&isSinglePage=1&isNeedFooter=1`
        this.dialogE9 = WeaTools.createDialog({
            title: getLabel(520145, "代理流程处理条件设置"),
            moduleName: "workflow",
            url: url,
            style: { width: 900,height:560 },
            callback: (datas) => {
                let data = {
                    conditionss: datas.conditionss,
                    conditioncn: datas.conditioncn,
                    ruleRelationship: datas.ruleRelationship,
                    conditionkeyid: params.linkid,
                };
                message.destroy();
                this.setConditionData(rowindex, data);
            }
        })
    }

    onFormChange = (datas) => {
        console.log(datas);
    }
    onSave = () => {
        this.dialogE9.close();
    }
    setConditionData(rowindex, changeData) {
        const datas = this.agentConditionData.slice();
        if (datas.length > rowindex) {
            const item = { ...datas[rowindex], ...changeData };
            datas.splice(rowindex, 1, item);
            this.setAgentConditionData([...datas]);
        }
    }
    
    startTimeChange(obj, formFlag) {

        // let formParams;
        // if(formFlag === 'batchEditForm'){
        //     formParams = this.batchEditForm.getFormParams();
        //
        // }else if(formFlag === 'addAgentForm') {
        //     formParams = this.addAgentForm.getFormParams();
        //
        // }else if(formFlag === 'editAgentForm'){
        //     formParams = this.editAgentForm.getFormParams();
        // }
        //
        // if (formParams.beginDate === formParams.endDate && formParams.beginDate !== '' && formParams.endTime !== '' ) {
        //
        //     let endTime = Number(formParams.endTime.replace(/:/g,''));
        //     let startTime =  Number(obj.beginTime.value.replace(/:/g,''));
        //
        //     if(endTime <= startTime){
        //         Modal.warning({
        //             title: '信息确认',
        //             content: '结束时间不能小于等于开始时间！',
        //             okText: '确定'
        //         });
        //         return ;
        //     }
        // }

    }

    endTimeChange(obj, formFlag) {

        // let formParams;
        //
        // if(formFlag === 'batchEditForm'){
        //     formParams = this.batchEditForm.getFormParams();
        //
        // }else if(formFlag === 'addAgentForm') {
        //     formParams = this.addAgentForm.getFormParams();
        //
        // }else if(formFlag === 'editAgentForm'){
        //     formParams = this.editAgentForm.getFormParams();
        // }
        //
        // if (formParams.beginDate === formParams.endDate && formParams.beginDate !== '' && formParams.beginTime !== '' ) {
        //
        //     let endTime =  Number(obj.endTime.value.replace(/:/g,''));
        //     let startTime = formParams.beginTime.replace(/:/g,'');
        //
        //     if(endTime <= startTime){
        //         Modal.warning({
        //             title: '信息确认',
        //             content: '结束时间不能小于等于开始时间！',
        //             okText: '确定'
        //         });
        //         return ;
        //     }
        // }

    }

    //保存验证时间
    verifyTime(formFlag) {

        let formParams;

        if (formFlag === 'batchEditForm') {
            formParams = this.batchEditForm.getFormParams();

        } else if (formFlag === 'addAgentForm') {
            formParams = this.addAgentForm.getFormParams();

        } else if (formFlag === 'editAgentForm') {
            formParams = this.editAgentForm.getFormParams();
        }

        if (formParams.beginTime !== '' && formParams.beginDate === '') {
            Modal.warning({
                title: getLabel(131329, '信息确认'),
                content: getLabel(127684, '设置开始时间必须设置开始日期！'),
                okText: getLabel(83446, '确定')
            });
            return false;
        }

        if (formParams.endTime !== '' && formParams.endDate === '') {
            Modal.warning({
                title: getLabel(131329, '信息确认'),
                content: getLabel(127685, '设置结束时间必须设置结束日期！'),
                okText: getLabel(83446, '确定')
            });
            return false;
        }

        if (formParams.beginDate !== '' && formParams.endDate !== '') {

            let startDate = Number(formParams.beginDate.replace(/-/g, ''));
            let endDate = Number(formParams.endDate.replace(/-/g, ''));

            if (endDate > startDate) {
                return true;
            } else if (endDate < startDate) {
                Modal.warning({
                    title: getLabel(131329, '信息确认'),
                    content: getLabel(127683, '结束时间不能小于等于开始时间！'),
                    okText: getLabel(83446, '确定')
                });
                return false;
            } else if (formParams.beginTime === '' || formParams.endTime === '') {
                return true;
            } else if (formParams.beginTime !== '' && formParams.endTime !== '') {
                let endTime = Number(formParams.endTime.replace(/:/g, ''));
                let startTime = Number(formParams.beginTime.replace(/:/g, ''));

                if (endTime <= startTime) {
                    Modal.warning({
                        title: getLabel(131329, '信息确认'),
                        content: getLabel(127683, '结束时间不能小于等于开始时间！'),
                        okText: getLabel(83446, '确定')
                    });
                    return false;
                }
            }

        }

        return true;
    }

    //设置不同tab的参数
    setParams(agented, agentFlag) {
        this.agented = agented;
        this.agentFlag = agentFlag;
    }

    setConditionByTree() {
        return 0;
    }

    // 切换tab
    setViewcondition(viewcondition) {
        this.viewcondition = viewcondition;
    }

    //验证重复
    verifyAgentOverlap(params = {}) {
        WORKFLOW_AGENT.verifyAgentOverlap(params).then(datas => {
            // this.repetitionValue = 0;
            if (datas.overlapCount > 0) {  //弹出重复处理选项(1、新代理去重复；2、新代理覆盖已重复)
                this.overlapIds = datas.overlapIds;
                this.repetitionValue = datas.overlapCount;
            } else {
                this.dataSave(params);
            }

        });
    }

    //编辑，批量编辑，代理条件，新建的保存
    dataSave(params = {}) {
        if (this.editAgentVisible) {
            message.loading(getLabel(383500, '正在修改，请稍候...'), 0);
            this.isDisabled = true;
            WORKFLOW_AGENT.editAndSaveOtherSave(params).then((datas) => {
                const { agentresult } = datas;
                if (agentresult === 'success') {
                    this.editAgent(false);
                    message.destroy();
                    message.success(getLabel(383312, '修改成功'));
                    this.reload();
                } else {
                    message.destroy();
                    message.error(getLabel(31436, '修改失败'));
                }
            })

        } else if (this.batchEditVisible) {
            message.loading(getLabel(383500, '正在修改，请稍候...'), 0);
            this.isDisabled = true;
            WORKFLOW_AGENT.batchEditAgentSave(params).then((datas) => {
                const { agentresult } = datas;
                if (agentresult === 'success') {
                    if (this.editAgentVisible) {
                        this.editAgent(false);
                    } else {
                        this.batchEdit(false);
                    }
                    message.destroy();
                    message.success(getLabel(383312, '修改成功'));
                    this.reload();
                } else {
                    message.destroy();
                    message.error(getLabel(31436, '修改失败'));
                }
            })
        } else if (this.addAgentVisible) {
            message.loading(getLabel(383498, '正在添加，请稍候...'), 0);
            this.isDisabled = true;
            WORKFLOW_AGENT.addAgentSave(params).then(datas => {
                const { agentresult } = datas;
                if (agentresult === 'success') {
                    this.addAgent(false);
                    message.destroy();
                    message.success(getLabel(83880, '添加成功'));
                    if (this.urlParams.isSingle == "true") {
                        try {
                            window.close();
                        } catch (e) { }
                    } else
                        this.reload();
                } else {
                    message.destroy();
                    message.error(getLabel(26772, '添加失败'));
                }
            });
        }
    }

    //重新加载
    reload() {
        this.isDisabled = false;
        const current = this.tableStore.current;
        this.doSearch({ current });
    }

    //保存模板
    saveAgentTemplate(params = {}) {
        message.loading(getLabel(23278, '正在保存，请稍后...'), 0);
        WORKFLOW_AGENT.saveAgentTemplate(params).then((datas) => {
            if (datas.api_status) {
                message.destroy();
                message.success(getLabel(83551, '保存成功'));
            } else {
                message.destroy();
                message.error(getLabel(84544, '保存失败'));
            }
        })
    }

    clearFormFields() {
        this.form.resetConditionValue();      //清除查询条件值
        this.form.updateFields(this.highSearchInitDate, false);
    }

    clearStatus() {
        this.showSearchAd = false;
        this.clearFormFields();
        this.addAgentFlag = 'addAgent';
        this.agented = 0;
        this.agentFlag = 0;
        this.viewcondition = 0;
        this.title = getLabel(17723, '流程代理');
    }

    getBackRunning() {
        return this.backRunning;
    }

    setBackRunning(val) {
        this.backRunning = val;
    }


}



